﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace MemoryIndexNet.Indexes
{
    public class UniqueEquatableIndex<TKey, T> : KeyedIndex<TKey, T>
        where TKey : IEquatable<TKey>
    {
        // TODO: Make immutable
        readonly IDictionary<TKey, List<T>> _underlying = new Dictionary<TKey, List<T>>();

        public UniqueEquatableIndex(IEnumerable<T> values, Func<T, TKey> keyExtractor)
            : base(keyExtractor)
        {
            // TODO: Check for nulls

            foreach (var value in values)
                Add(value);
        }

        List<T> GetValueContaierOrNull(TKey key)
        {
            List<T> values;

            if (_underlying.TryGetValue(key, out values))
                return values;
            else
                return null;
        }

        List<T> GetOrCreateValueContaier(TKey key)
        {
            var values = GetValueContaierOrNull(key);

            if (values != null)
                return values;

            values = new List<T>();
            _underlying.Add(key, values);
            return values;
        }

        private void Add(T value)
        {
            var key = KeyExtractor(value);
            GetOrCreateValueContaier(key).Add(value);
        }

        public IEnumerable<T> GetByKey(TKey key)
        {
            List<T> values;

            if (_underlying.TryGetValue(key, out values))
                return values.AsReadOnly();
            else
                return Enumerable.Empty<T>();
        }
    }
}
